<template>
  <div class="wrapper">
    <!-- 头部 -->
    <header>
      <div class="title">消息中心</div>
    </header>

    <!-- 消息列表 -->
    <div class="message-list">
      <div 
        v-for="(msg, index) in messages" 
        :key="index" 
        class="message-item"
        @click="toMessageDetail(msg)"
      >
        <img 
          :src="msg.avatar" 
          class="avatar" 
          @error="handleAvatarError"
        >
        <div class="content">
          <div class="top">
            <span class="name">{{ msg.name }}</span>
            <span class="time">{{ msg.time }}</span>
          </div>
          <div class="bottom">
            <p class="last-message">{{ msg.lastMessage }}</p>
            <span class="unread" v-if="msg.unread">{{ msg.unread }}</span>
          </div>
        </div>
      </div>
    </div>

    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Footer from '../components/Footer.vue';
import { getMessageList } from '../api/message';
import { useUserInfoStore } from '../stores/user';
import { handleAvatarUrl, handleAvatarError } from '@/utils/imageUtils';

const router = useRouter();
const userStore = useUserInfoStore();
const messages = ref([]);

// 获取消息列表
const fetchMessages = async () => {
  try {
    const userId = userStore.userInfo.id;
    const res = await getMessageList(userId);
    
    if(res.code === 0) {
      const messageMap = new Map();
      const unreadCountMap = new Map();
      
      res.data.forEach(msg => {
        const otherId = msg.senderId === userId ? msg.receiverId : msg.senderId;
        if (msg.status === 0 && msg.senderId !== userId) {
          unreadCountMap.set(otherId, (unreadCountMap.get(otherId) || 0) + 1);
        }
      });
      
      for (const msg of res.data) {
        const otherId = msg.senderId === userId ? msg.receiverId : msg.senderId;
        const otherUserInfo = msg.recipientInfo || {};
        const avatar = otherUserInfo.avatar || '';
        
        if (!messageMap.has(otherId) || messageMap.get(otherId).createTime < msg.createdTime) {
          messageMap.set(otherId, {
            id: msg.id,
            name: otherUserInfo.username || `用户${otherId}`,
            avatar: handleAvatarUrl(avatar),
            lastMessage: msg.message,
            time: formatTime(msg.createdTime),
            unread: unreadCountMap.get(otherId) || 0,
            receiverId: otherId,
            createTime: new Date(msg.createdTime).getTime()
          });
        }
      }
      
      messages.value = Array.from(messageMap.values());
      messages.value.sort((a, b) => b.createTime - a.createTime);
    }
  } catch (error) {
    console.error('获取消息列表失败:', error);
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  } else if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
    return '昨天';
  } else {
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
  }
};

// 跳转到消息详情页
const toMessageDetail = (msg) => {
  router.push({
    name: 'message-detail',
    params: {
      id: msg.receiverId.toString()
    },
    query: {
      receiverId: msg.receiverId.toString(),
      businessName: msg.name,
      businessAvatar: msg.avatar
    }
  });
};

onMounted(() => {
  fetchMessages();
});
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 14vw;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 3vw 4vw;
  background-color: #ff7043;
}

header .title {
  font-size: 4.5vw;
  font-weight: bold;
  color: #fff;
}

.message-list {
  background-color: #fff;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 3vw 4vw;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.message-item:active {
  background-color: #f9f9f9;
}

.avatar {
  width: 12vw;
  height: 12vw;
  border-radius: 50%;
  margin-right: 3vw;
}

.content {
  flex: 1;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vw;
}

.name {
  font-size: 4vw;
  color: #333;
  font-weight: 500;
}

.time {
  font-size: 3vw;
  color: #999;
}

.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  font-size: 3.5vw;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread {
  background-color: #ff7043;
  color: #fff;
  font-size: 3vw;
  padding: 0.5vw 2vw;
  border-radius: 4vw;
  margin-left: 2vw;
}
</style>